// 获取应用实例
const brtc = require('../../../../static/baidu.rtc.mp.sdk.js');

var BRTCClient = brtc.BRTC;

const app = getApp();

String.prototype.hashCode = function() {
    var hash = 0;
    if (this.length == 0) {
        return hash;
    }
    for (var i = 0; i < this.length; i++) {
        var char = this.charCodeAt(i);
        hash = ((hash<<5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
};

var display_name = 'MiniApp Client';

Page({
    onReady(res) {
        this.remotevideo = wx.createLivePlayerContext('player', this);
        this.localvideo = wx.createLivePusherContext('pusher', this);
        var that = this;
        wx.getStorage({
            key: 'roomname',
            success(res) {
                that.setData({RoomName: res.data});
            }
        });
        wx.getStorage({
            key: 'appid',
            success(res) {
                that.setData({AppID: res.data});
            }
        });
    },
    onUnload() {
      console.log(this.data.isManualExit,'这是啥啊');
      if (this.data.isManualExit) {
        console.log("用户主动退出");
      
      } else {
        console.log("非用户主动退出");
        this.localvideo.stop({
          success: res => {
              console.log('stop pusher success');
          },
          fail: res => {
              console.log('stop pusher fail');
          }
        });
        this.remotevideo.stop({
            success: res => {
                console.log('stop player success');
            },
            fail: res => {
                console.log('stop player fail');
            }
        });
        this.setData({
            hasLogined: false
        });
        BRTCClient.BRTC_Stop();
      }
     
    },
    data: {
        motto: '百度智能云RTC',
        login: '进入房间',
        logout: '结束录制',
        userInfo: {},
        isManualExit: false, // 标记是否主动退出
        hasUserInfo: false,
        hasLogined: false,
        sendmsg: '发送消息',
        textMessage: '众里寻他千百度~',
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        RoomName: '8888',
        Messages: '8888',
        AppID: 'apppikmjgngjhig',
        PlayUrl: '',
        PushUrl: '',
    },
    // 事件处理函数
    bindViewTap: function () {
        wx.navigateTo({
            url: '../logs/logs'
        });
    },
    onLoad: function (query) {

      if (typeof query.room_id !== 'undefined') {
        this.setData({
          RoomName: query.room_id
          });
    }
    if (typeof query.message !== 'undefined') {
      this.setData({
        Message: query.message
        });
  }
        if (typeof query.appid !== 'undefined') {
            this.setData({
                AppID: query.appid
              });
        }

        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });

        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            });
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                });
            };
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo;
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    });
                }
            });
        }
        this.connectBRTC()
    },
    getUserInfo: function (e) {
        console.log(e);
        app.globalData.userInfo = e.detail.userInfo;
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        });
    },

    connectBRTC: function (e) {
        var AppId = this.data.AppID;

        this.setData({
            AppID: AppId
        });
        if (AppId === 'appid') {
            AppId = 'apppikmjgngjhig';
        }

        if (AppId === '') {
            wx.showModal({
                title: '提示',
                content: 'AppID不合法, 请填入合法的AppID, 谢谢!',
                success (res) {
                  if (res.confirm) {

                  } else if (res.cancel) {
                    wx.navigateTo({
                        url: '../logs/logs'
                    });
                  }
                }
              });
 
            return ;
        }

        var RoomName = this.data.RoomName;
        wx.setStorage({
            key: 'roomname',
            data: RoomName
        });
        this.setData({
            RoomName: RoomName
        });
        var UserID = (1000000 + Math.floor(Math.random() * 10000)).toString();
        if (this.data.hasUserInfo) {
            UserID = this.data.userInfo.nickName.hashCode().toString();
            display_name = this.data.userInfo.nickName;
        }
        var Token = 'no_token';

        var that = this;

        BRTCClient.BRTC_Start({
            server: 'wss://rtc.exp.bcelive.com/janus',
            appid: AppId,
            token: Token,
            roomname: RoomName,
            userid: UserID,
            displayname: display_name,
            aspublisher: true,
            autosubscribe: true,
            remotevideoon: function(idx) {
                console.log('remotevideoon, index:' + idx);
            },
            remotevideooff: function(idx) {
                console.log('remotevideooff, index:' + idx);
            },
            remotevideocoming: function(id, display, attribute, pullurl) {
                console.log('remotevideocoming, feedid:' + id + ' display:' + display
                + ' a:' + attribute + ' Pull URL is:' + pullurl);
                // rtmp://endpoint/%a/%rn/%f?sdkJoined=true&userId=%u&token=%t
                // that.setData({
                //     PlayUrl: 'rtmp://rtcplay.exp.bcelive.com:8935/' + AppId + '/' + RoomName + '/' + id + '?sdkJoined=true&userId=' + UserID + '&token=' + Token
                // });
                that.setData({
                    PlayUrl: pullurl
                });
                that.remotevideo.stop();
                that.remotevideo.play();
            },
            remotevideoleaving: function(id) {
                console.log('remotevideoleaving, feedid:' + id);
            },
            userevent_joinedroom: function(id, display, attribute) {
                console.log('userevent_joinedroom id: ' + id + ', display: ' + display + ', attribute:' + attribute);
            },
            userevent_leavingroom: function(id, display) {
                console.log('userevent_leavingroom id: ' + id + ', display: ' + display);
            },
            success: function(pushurl) {
                that.setData({
                    hasLogined: true
                });
                console.log('success, Push URL is:' + pushurl);
                // rtmp://endpoint/%a/%rn/%u?sdkJoined=true&token=%t
                // that.setData({
                //     PushUrl: 'rtmp://rtcplay.exp.bcelive.com:8935/' + AppId + '/' + RoomName + '/' + UserID + '?sdkJoined=true&token=' + Token
                // });
                that.setData({
                    PushUrl: pushurl
                });
                that.localvideo.stop();
                that.localvideo.start();
            },
            localvideopublishing: function() {

            },
            localvideopublished_ok: function() {

            },
            remotevideo_closed:  function(feedid) {
                console.log('remotevideo_closed(feedid: ' + feedid + ') by server, please do SubScribing again');
            },
            error: function(error) {
                wx.showModal({
                    title: '提示',
                    content: '登录失败,请检查AppID等参数,谢谢!',
                    success: function (res) {
                        if (res.confirm) {
                        }
                    }
                });
            },
            destroyed: function(error) {

            },
            onlocalstream: function(stream,name) {
                //local stream for display sonic wave
                console.log('onlocalstream name: ' + name);
            },
            onlocalstream_end: function(name) {
                //end event of local stream
                console.log('onlocalstream_end name: ' + name);
            },
            onmessage: function(msg) {
                // event onmessage.
                console.log('onmessage id: ' + msg.id + ' data: '+ msg.data);
            },
            onattribute: function(a) {
                // event onattribute
                console.log('onattribute id: ' + a.id + ' attribute: '+ a.attribute);
            },
            reportmonitordata: false,
        });
    },
    logoutBRTC: function (e) {
      console.log("录制已结束点击");
      wx.showModal({
        title: '提示',
        content: '确定结束录制并上传吗？',
        success: (res) => {  // ✅ 改用箭头函数
          if (res.confirm) {
            console.log("录制已结束");
            this.setData({ isManualExit: true });
            this.logoutBRTCB_Send(); 
            this.logoutBRTCB(); // 现在可以正确调用
          } else if (res.cancel) {
            console.log("用户取消了操作");
          }
        }
      });
      console.log(abs);
    },
    logoutBRTCB_Send: function (e) {
      let url = 'data/api.auth.order/du_video_record';
      console.log(this.data)
      let params = {
          record_id:this.data.RoomName,
      }
      
      getApp()._post_form(url, params, results => {
          console.log(results);
          // this.setData({
          //     caller:results.data.caller,
          //     listener:results.data.listener,
          //     message:results.data.message,
          // })
      });
    },
    logoutBRTCB: function (e) {
      this.localvideo.stop({
        success: res => {
            console.log('stop pusher success');
        },
        fail: res => {
            console.log('stop pusher fail');
        }
    });
    this.remotevideo.stop({
        success: res => {
            console.log('stop player success');
        },
        fail: res => {
            console.log('stop player fail');
        }
    });
    this.setData({
        hasLogined: false
    });
    BRTCClient.BRTC_Stop();
    wx.reLaunch({
      url: '/pages/home/index'
    });
  },
    bindInputRoomName: function (e) {
        this.data.RoomName = e.detail.value;
        wx.setStorage({
            key: 'roomname',
            data: this.data.RoomName
        });
    },
    bindInputAppID: function (e) {
        this.data.AppID = e.detail.value;
        wx.setStorage({
            key: 'appid',
            data: this.data.AppID
        });
    },
    bindSendDanmu: function () {
    },
    bindInputTextMsg: function (e) {
        this.data.textMessage = e.detail.value;
    },
    bindSendTextMsg: function () {
        BRTCClient.BRTC_SendMessageToUser(this.data.textMessage);
    },
    statechange: function () {

    },
    error: function () {

    },
});
